<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\facade\Session;
use think\exception\ValidateException;
use service\JsonService as Json;

use app\common\model\SystemAdmin;

use app\common\validate\SystemAdminValidate;

class LoginController
{
    /** 登陆页面渲染 */
    public function login()
    {
        return view();
    }

    /** 登陆 */
    public function login_data()
    {
        $data = input('');

        try{
            validate(SystemAdminValidate::class)->scene('login')->check($data);
        }catch(ValidateException $e){
            return json::fail($e->getError());
        }

        $info = SystemAdmin::where(['account' => $data['account']])->find();

        if(!$info){
            return json::fail('该账号不存在');
        }

        if($info['password'] != setPass($data['password'])){
            return json::fail($info['password']);
        }

        SystemAdmin::edit(['id' => $info['id'], 'last_time' => time()]);
        $infoArr = $info->toArray();
        Session::set('token', $infoArr);

        return json::success('登陆成功');
    }

    /** 退出登陆 */
    public function login_out()
    {
        Session::delete('token');
        return view('login/login');
    }
}
